let __curUrl = "";
let createPromisedFun = (name, d = {})=> {
    return (opt) => {
        return new Promise(function (resolve, reject) {
            wx[name]({
                success: (res) => {
                    resolve(res);
                },
                fail(e) {
                    reject(e);
                },
                ...d,
                ...opt
            });
        });
    };
};

let createParamFun = (fun, ...args) => {
    setNavigationBarTitle()
};

let createFun = (name) => {
    return (opt = {}) => {
        wx[name]({
            ...opt
        });
    }
};

export let scanCode = createPromisedFun('scanCode');
export let previewImage = createPromisedFun('previewImage');
export let getImageInfo = createPromisedFun('getImageInfo');
export let saveImageToPhotosAlbum = createPromisedFun('saveImageToPhotosAlbum');
export let chooseVideo = createPromisedFun('chooseVideo');
export let saveVideoToPhotosAlbum = createPromisedFun('saveVideoToPhotosAlbum');
export let chooseImage = createPromisedFun('chooseImage');
export let getFileInfo = createPromisedFun('getFileInfo');
export let getSavedFileList = createPromisedFun('getSavedFileList');
export let getSavedFileInfo = createPromisedFun('getSavedFileInfo');
export let removeSavedFile = createPromisedFun('removeSavedFile');
export let openDocument = createPromisedFun('openDocument');
export let getLocation = createPromisedFun('getLocation');
export let chooseLocation = createPromisedFun('chooseLocation');
export let openLocation = createPromisedFun('openLocation');
export let getNetworkType = createPromisedFun('getNetworkType');
export let setClipboardData = createPromisedFun('setClipboardData');
export let getClipboardData = createPromisedFun('getClipboardData');
export let setScreenBrightness = createPromisedFun('setScreenBrightness');
export let getScreenBrightness = createPromisedFun('getScreenBrightness');
export let keepScreenOn = createPromisedFun('keepScreenOn');
export let addPhoneContact = createPromisedFun('addPhoneContact');
export let showLoading = createPromisedFun('showLoading');
export let setNavigationBarTitle = createPromisedFun('setNavigationBarTitle');
export let setTabBarBadge = createPromisedFun('setTabBarBadge');
export let removeTabBarBadge = createPromisedFun('removeTabBarBadge');
export let showTabBarRedDot = createPromisedFun('showTabBarRedDot');
export let hideTabBarRedDot = createPromisedFun('hideTabBarRedDot');
export let setTabBarStyle = createPromisedFun('setTabBarStyle');
export let setTabBarItem = createPromisedFun('setTabBarItem');
export let showTabBar = createPromisedFun('showTabBar');
export let hideTabBar = createPromisedFun('hideTabBar');
export let requestPayment = createPromisedFun('requestPayment');
export let showToast = createPromisedFun('showToast', {
    icon: "none"
});
export let hideToast = createFun('hideToast');
export let hideLoading = createFun('hideLoading');


export let showNavigationBarLoading = createFun('showNavigationBarLoading');
export let hideNavigationBarLoading = createFun('hideNavigationBarLoading');
export let makePhoneCall = createFun('makePhoneCall');


export function createMapContext() {
    let mapContext = wx.createMapContext();
    return mapContext;
}


export function createLivePusherContext() {
    let livePusherContext = wx.createLivePusherContext();
    return livePusherContext;
}

export function createLivePlayerContext() {
    let livePlayerContext = wx.createLivePlayerContext();
    return livePlayerContext;
}

export function createCameraContext() {
    let cameraContext = wx.createCameraContext();
    return cameraContext;
}

export function createVideoContext() {
    let videoContext = wx.createVideoContext();
    return videoContext;
}

export function createInnerAudioContext() {
    let innerAudioContext = wx.createInnerAudioContext();
    return innerAudioContext;
}

export function getRecorderManager() {
    let recorderManager = wx.getRecorderManager();
    return recorderManager;
}

export function getBackgroundAudioManager() {
    let backgroundAudioManager = wx.getBackgroundAudioManager();
    return backgroundAudioManager;
}

export const updateApp = (opt) => {
    const updateManager = wx.getUpdateManager();
    updateManager.onUpdateReady(function () {
        wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: (res) => {
                if (res.confirm) {
                    updateManager.applyUpdate()
                }
            },
            ...opt
        })
    })
};

export function navigateTo(url) {
    if (url) {
        __curUrl = url;
        wx.setStorageSync("__curUrl", url);
        wx.navigateTo({
            url: url
        })
    } else {
        throw new Error("url not empty");
    }
}

export function redirectTo(url) {
    wx.setStorageSync("__curUrl", url);
    wx.redirectTo({
        url: url
    })
}

export function changeTo(url, opt = {}) {
    let fun = navigateTo;
    if (opt && opt.type === "redirect") {
        fun = redirectTo;
    }
    return fun(url);
}

export function changeToPage(pageName, p = "index", opt = {}) {
    return changeTo(`/pages/${pageName}/${p}`, opt);
}


export function switchTab(url, opt) {
    wx.setStorageSync("__curUrl", url);
    wx.switchTab({
        url: url,
    })
}

export function switchPage(pageName, p = "index", opt = {}) {
    switchTab(`/pages/${pageName}/${p}`, opt);
}

export function navigateBack(delta) {
    wx.navigateBack({
        delta: delta
    });
}

export function reLaunch(url) {
    wx.reLaunch(url);
}


export function getCurUrl() {
    return wx.getStorageSync("__curUrl");
}

export function initWx() {
    wx.removeStorageSync("__curUrl");
}


export let uploadFile = (url, filePath, onSend = (u)=>{}, formData = {})=> {
    return new Promise(function (resolve, reject) {
        let uploadTask  = wx.uploadFile({
            url: url,
            filePath: filePath,
            name: 'file',
            formData:formData,
            success: function(res){
                resolve(res, uploadTask);
            },
            fail(e) {
                reject(e, uploadTask);
            }
        });
        if (onSend) {
            onSend(uploadTask);
        }
    });
};

export let downloadFile = (url, filePath, onSend = (u)=>{}) => {
    return new Promise(function (resolve, reject) {
        let downloadTask = wx.downloadFile({
            url: url,
            success: function(res) {
                resolve(res, downloadTask);
            },
            fail(e) {
                reject(e, downloadTask);
            }
        });
        if (onSend) {
            onSend(downloadTask);
        }
    });
};

export function setNavBarTitle(title) {
    wx.setNavigationBarTitle({
        title: title
    })
}

export function stopPullDownRefresh() {
    wx.stopPullDownRefresh();
}

export function showPageLoading(text = "加载中") {
    showNavigationBarLoading();
    wx.showLoading({
        title: text
    })
}

export function setStorageSync(k, v) {
    wx.setStorageSync(k, v);
}

export function getStorageSync(k) {
    return wx.getStorageSync(k);
}

export function getStorageInfoSync() {
    return wx.getStorageInfoSync();
}

export function startAccelerometer() {
    return wx.startAccelerometer();
}

export function stopAccelerometer() {
    return wx.stopAccelerometer();
}

export function startCompass() {
    return wx.startCompass();
}

export function stopCompass() {
    return wx.stopCompass();
}

export function removeStorageSync(k) {
    try {
        wx.removeStorageSync(k)
    } catch (e) {
        throw e;
    }
}

export function clearStorageSync() {
    wx.clearStorageSync();
}

export function getSystemInfoSync() {
    try {
        return wx.getSystemInfoSync()
    } catch (e) {
        throw e;
    }
}

export function hidePageLoading() {
    hideNavigationBarLoading();
    wx.hideLoading();
}

export function pageScrollTo(d, duration = 300) {
    wx.pageScrollTo({
        scrollTop: d,
        duration: duration
    })
}

export function showModal(title, content) {
    return new Promise(function (resolve, reject) {
        wx.showModal({
            title: title,
            content: content,
            success: function(res) {
                if (res.confirm) {
                    resolve(res);
                } else if (res.cancel) {
                    reject();
                }
            },
            fail(e) {
                reject(e);
            }
        })
    });
}


export function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    var len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
        v1.push('0')
    }
    while (v2.length < len) {
        v2.push('0')
    }

    for (var i = 0; i < len; i++) {
        var num1 = parseInt(v1[i])
        var num2 = parseInt(v2[i])

        if (num1 > num2) {
            return 1
        } else if (num1 < num2) {
            return -1
        }
    }

    return 0
}